<template>
  <div>
    <div style="display: flex; align-items: center; justify-content: center; flex-direction: column">
      <svg-icon iconClass="coffee" size="70"></svg-icon>
      <p>您已工作了：{{ diffTime }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onUnmounted, onMounted } from 'vue'
  let year = new Date().getFullYear()
  let month = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1
  let date = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
  const workingTime = ref({
    date: `${year}-${month}-${date}`,
    startTime: new Date().getTime(),
    pauseTime: 0,
    startPauseTime: 0,
  })
  let localWorkingTime = JSON.parse(localStorage.getItem('workingTime') as any) || null
  const timestamp1 = ref()
  const timestamp2 = ref()
  if (!localWorkingTime) {
    localStorage.setItem('workingTime', JSON.stringify(workingTime.value as any))
  } else {
    if (localWorkingTime.date == workingTime.value.date) {
      timestamp1.value = localWorkingTime.startTime
    } else {
      localStorage.setItem('workingTime', JSON.stringify(workingTime.value as any))
    }
  }

  let intervalId: any = null

  const diffTime = ref('')

  function calculateDiffTime() {
    const diff = timestamp2.value - timestamp1.value // 计算时间戳之间的差值（毫秒）
    const seconds = Math.floor((diff / 1000) % 60) // 计算相差的秒数
    const minutes = Math.floor((diff / (1000 * 60)) % 60) // 计算相差的分钟数
    const hours = Math.floor(diff / (1000 * 60 * 60)) // 计算相差的小时数
    diffTime.value = `${hours}小时${minutes}分钟${seconds}秒`
  }
  onMounted(() => {
    intervalId = setInterval(() => {
      if (localWorkingTime?.date == workingTime?.value?.date) {
        timestamp1.value = localWorkingTime.startTime
        timestamp2.value = new Date().getTime()
        calculateDiffTime()
      } else {
        localWorkingTime = JSON.parse(localStorage.getItem('workingTime') as any) || null
      }
    }, 1000)
  })
  onUnmounted(() => {
    // 清除定时器
    if (intervalId) {
      clearInterval(intervalId)
    }
  })
</script>

<style scoped></style>
